import string
from django.http.response import JsonResponse
from django.shortcuts import render, redirect, reverse
from django.views.decorators.http import require_GET, require_http_methods
import random
from django.core.mail import send_mail
from .forms import RegisterForm, LoginForm
from .models import CaptchaModel
from django.contrib.auth import get_user_model, login, logout

User = get_user_model()

# Create your views here.

@require_http_methods(['GET', 'POST'])
def my_login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data.get('email')
            remember = form.cleaned_data.get('remember')
            user = User.objects.filter(email=email).first()
            login(request, user)
            #判断是否记住我
            if not remember:
                # 如果没有点击记住我，设置过期时间为0，浏览器关闭后就会过期
                request.session.set_expiry(0)
            return redirect('/')
        else:
            print(form.errors)
            return redirect(reverse('myauth:login'))



@require_http_methods(['GET', 'POST'])
def register(request):
    #初次进入页面的GET请求
    if request.method == 'GET':
        return render(request, 'register.html')
    #提交表单的POST请求
    else:
        form = RegisterForm(request.POST)
        # 验证用户注册的信息是否合法
        if form.is_valid():
            email = form.cleaned_data.get('email')
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            User.objects.create_user(email=email, username=username, password=password)
            return redirect(reverse('myauth:login'))
        else:
            return render(request, 'register.html', context={'form': form})

def my_logout(request):
    logout(request)
    return redirect('/')


@require_GET
def send_captcha(request):
    email = request.GET.get('email')
    captcha = "".join(random.sample(string.digits, 4))
    send_mail('TechSphere注册验证码', f'您的验证码是：{captcha}', from_email=None, recipient_list=[email])
    CaptchaModel.objects.update_or_create(email=email, defaults={'captcha': captcha})
    return JsonResponse({'code': 200, 'message': '验证码发送成功！'})
